package tasks.io.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tasks.io.core.SystemTimer;
import tasks.io.core.thread.AbstractSynTask;

import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;


public class ReconnTask extends AbstractSynTask {
    private static final Logger log = LoggerFactory.getLogger(ReconnTask.class);

    ClientChannelContext clientChannelContext = null;
    Client client = null;


    public ReconnTask(ClientChannelContext clientChannelContext, Client client, Executor executor) {
        super(executor);
        this.clientChannelContext = clientChannelContext;
        this.client = client;
    }

    @Override
    public boolean isNeededExecute() {
        return false;
    }

    @Override
    public void runTask() {
        clientChannelContext.getReconnCount().incrementAndGet();
        ReentrantReadWriteLock closeLock = clientChannelContext.closeLock;
        WriteLock writeLock = closeLock.writeLock();
        writeLock.lock();
        try {
            if (!clientChannelContext.isClosed) //已经连上了，不需要再重连了
            {
                return;
            }
            long start = SystemTimer.currTime;
            client.reconnect(clientChannelContext, 2);
            long end = SystemTimer.currTime;
            long iv = end - start;


            log.error("{}, 第{}次重连,重连耗时:{} ms", clientChannelContext, clientChannelContext.getReconnCount(), iv);


        } catch (java.lang.Throwable e) {
            log.error(e.toString(), e);
        } finally {
            writeLock.unlock();
        }

    }
}
